package com.itheima.reggie.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.domain.Dish;
import com.itheima.reggie.domain.DishFlavor;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DishFlavorMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    // 菜品列表
    @Override
    public Page<Dish> findByPage(Integer pageNum, Integer pageSize, String name) {

        // a. 分页+条件查询菜品  select * from dish where name like '%鱼%' order by update_time desc limit 0,10
        // 1.构建条件
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.like(StrUtil.isNotEmpty(name), Dish::getName, name); // where name like '%鱼%'
        qw.orderByDesc(Dish::getUpdateTime); // order by update_time desc
        // 2.构建分页
        Page<Dish> page = new Page<>(pageNum, pageSize); // limit 0,10
        // 3.分页查询
        page = dishMapper.selectPage(page, qw);

        // 4.遍历菜品
        for (Dish dish : page.getRecords()) {
            // b. 查询分类名称  select * from category where id = 1397844263642378242
            Category category = categoryMapper.selectById(dish.getCategoryId());
            dish.setCategoryName(category.getName());

            // c.查询口味列表 select * from dish_flavor where dish_id = 1397850392090947585
            LambdaQueryWrapper<DishFlavor> qw2 = new LambdaQueryWrapper<>();
            qw2.eq(DishFlavor::getDishId, dish.getId());  // where dish_id = 1397850392090947585
            List<DishFlavor> flavorList = dishFlavorMapper.selectList(qw2);
            dish.setFlavors(flavorList);
        }

        // 5.返回分页
        return page;
    }

    // 新增菜品
    @Override
    public void save(Dish dish) {
        // 1.保存菜品基本信息  insert into dish() values();
        log.info("菜品保存前ID：{}", dish.getId());
        dishMapper.insert(dish);
        log.info("菜品保存后ID：{}", dish.getId());

        // 2.取出前端提供口味列表并遍历
        List<DishFlavor> flavorList = dish.getFlavors();
        for (DishFlavor dishFlavor : flavorList) {
            // 2-1 关联菜品id
            dishFlavor.setDishId(dish.getId());
            // 2-2 保存数据库  insert into dish_flavor() values();
            dishFlavorMapper.insert(dishFlavor);
        }

    }

    // 回显菜品
    @Override
    public Dish findById(Long dishId) {
        // 1.查询菜品基本信息   select * from dish where id = 1632199055591378946
        Dish dish = dishMapper.selectById(dishId);

        // 2.构建口味查询条件 select * from dish_flavor where dish_id = 1632199055591378946
        LambdaQueryWrapper<DishFlavor> qw = new LambdaQueryWrapper<>();
        qw.eq(DishFlavor::getDishId, dishId); //  where dish_id = 1632199055591378946

        // 3.查询口味列表
        List<DishFlavor> flavorList = dishFlavorMapper.selectList(qw);

        // 4.将口味封装到菜品
        dish.setFlavors(flavorList);

        // 5.返回菜品
        return dish;
    }

    // 修改菜品
    @Override
    public void updateDish(Dish dish) {
        // 1.直接修改菜品基本信息  update dish set xx=xxx where id = 1
        dishMapper.updateById(dish);

        // 2.根据菜品id删除旧口味  delete from dish_flavor where dish_id = 1
        /*LambdaQueryWrapper<DishFlavor> qw = new LambdaQueryWrapper<>();
        qw.eq(DishFlavor::getDishId,dish.getId());// where dish_id = 1
        dishFlavorMapper.delete(qw);*/
        dishFlavorMapper.deleteByDishId(dish.getId());

        // 3.获取前端新提供的口味列表 遍历
        for (DishFlavor flavor : dish.getFlavors()) {
            // 3-1 口味关联菜品id
            flavor.setDishId(dish.getId());
            // 3-2 保存数据库
            dishFlavorMapper.insert(flavor);
        }

    }

    // 起售、停售
    @Override
    public void updateStatus(Integer status, List<Long> ids) {

        // 对集合进行非空判断
        if (CollUtil.isNotEmpty(ids)) {
            // 遍历ids集合
            for (Long id : ids) {
                // 封装更新数据
                Dish dish = new Dish();
                dish.setId(id);
                dish.setStatus(status);
                // 更新数据库
                dishMapper.updateById(dish);
            }
        }
    }

    // 菜品删除
    @Override
    public void deleteDish(List<Long> ids) {
        // 1.查询菜品状态 select count(*) from dish where id in(1632199055591378946,1413384757047271425) and status = 1
        LambdaQueryWrapper<Dish> dishQw = new LambdaQueryWrapper<>();
        dishQw.in(Dish::getId,ids); // where id in(1632199055591378946,1413384757047271425)
        dishQw.eq(Dish::getStatus,1); // and status = 1
        Integer dishCount = dishMapper.selectCount(dishQw);// select count(*) from dish
        // 2.判断是否有起售菜品
        if (dishCount>0) {
            throw new CustomException("有起售菜品，无法删除");
        }
        // 3.批量删除菜品 delete from dish where id in (1632199055591378946,1413384757047271425)
        dishMapper.deleteBatchIds(ids);

        // 4.删除菜品对应口味  delete from dish_flavor where dish_id in (1632199055591378946,1413384757047271425)
        LambdaQueryWrapper<DishFlavor> flavorQw = new LambdaQueryWrapper<>();
        flavorQw.in(DishFlavor::getDishId,ids);  // where dish_id in (1632199055591378946,1413384757047271425)
        dishFlavorMapper.delete(flavorQw);
    }

    @Override
    public List<Dish> findListBySetmeal(Long categoryId, String name) {
        //构建条件
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        //如果name是null就执行查询菜品
        qw.like(StrUtil.isNotEmpty(name),Dish::getName,name);
        //如果categoryid是null就执行模糊查询
        qw.eq(categoryId != null,Dish::getCategoryId, categoryId);

        //调用mapper回显菜品或模糊查询
        return dishMapper.selectList(qw);
    }

    @Override
    public List<Dish> list(Long categoryId, Integer status) {
        // 1.查询菜品 select * from dish where category_id = ? and status = ?
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.eq(Dish::getCategoryId,categoryId);
        qw.eq(Dish::getStatus,status);
        List<Dish> dishList = dishMapper.selectList(qw);

        // 2.遍历菜品列表
        dishList.forEach(dish -> {
            // 3.根据菜品id查询口味列表 select * from dish_flavor where dish_id = ?
            LambdaQueryWrapper<DishFlavor> qw2 = new LambdaQueryWrapper<>();
            qw2.eq(DishFlavor::getDishId,dish.getId());
            List<DishFlavor> flavorList = dishFlavorMapper.selectList(qw2);
            // 封装到菜品中
            dish.setFlavors(flavorList);
        });

        // 返回菜品列表
        return dishList;
    }
}
